from openpyxl import Workbook
from openpyxl.reader.excel import load_workbook


def save():
    # 创建一个新的工作簿
    wb = Workbook()

    # 获取活动的worksheet
    sheet = wb.active

    # 在A1单元格写入值
    sheet['A1'] = 'Hello, openpyxl!'

    # 保存文件
    wb.save(filename='example_new.xlsx')

def read():
    # 加载一个现有的Excel文件
    wb = load_workbook(r'liaoning.xlsx')

    # 获取活动的worksheet（默认打开的sheet）
    ws = wb.active

    # 读取A1单元格的值
    print(ws['A1'].value)
    ws['A1'] = 'Modified content'
    wb.save('example.xlsx')
    # 读取整行或整列的数据
    # print(ws['A'])  # 读取整列A的数据
    # print(ws[1])  # 读取第一行的数据
    pass

def load_read():
    from openpyxl import load_workbook

    # 加载一个现有的Excel文件
    wb = load_workbook('liaoning.xlsx')
    ws = wb.active

    # 遍历行和列（使用for循环）
    for row in ws.iter_rows():  # values_only=True只获取值，不获取单元格对象。
        print(row)


def read_cells_with_names():
    """读取Excel文件并打印所有单元格的名称和值"""
    wb = load_workbook(filename=r'liaoning.xlsx')
    ws = wb.active

    print(f"开始读取工作表: {ws.title}")
    for row in ws.iter_rows():
        for cell in row:
            # 获取单元格坐标（如A1、B3等）
            cell_name = cell.coordinate
            # 获取单元格值
            cell_value = cell.value
            # cell.value = '1'
            print(f"单元格 {cell_name}: {cell_value}")
    wb.save('example3.xlsx')
    wb.close()

if __name__ == '__main__':
    # save()
    # read()
    # load_read()
    read_cells_with_names()
    pass
